﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

public partial class _Default : System.Web.UI.Page
{
    private readonly string appid = ConfigurationManager.AppSettings["corpid"];//企业微信企业id
    private readonly string appsecret = ConfigurationManager.AppSettings["corpsecret"];//企业微信应用中
    private readonly string url = ConfigurationManager.AppSettings["url"];//要访问的网站，需和企业微信中应用中信任域名相同
    private readonly string agentid = ConfigurationManager.AppSettings["agentid"];//应用AgentId

    protected void Page_Load(object sender, EventArgs e)
    {
        //1 第一步：用户同意授权，获取code
        string code = Request.QueryString["code"];
        if (code == null || code == "")
        {
            //以snsapi_userinfo为scope发起的网页授权，是用来获取用户的基本信息的。但这种授权需要用户手动同意，并且由于用户同意过，所以无须关注，就可在授权后获取该用户的基本信息
            Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + url + "&response_type=code&scope=snsapi_privateinfo&agentid=" + agentid + "&state=STATE&connect_redirect=1#wechat_redirect");
        }
        string oToken = GetQiyAccess_token();  //获取token
        UserInfo2 userInfo = GetQiyGetUserinfo2(oToken, code);
        //userdetail detail = getuserdetail2(oToken, userInfo.UserId);
        string get_phone = "select * from WxWork.[dbo].[t_UserInfo] where userid='{0}' ";
        get_phone = string.Format(get_phone, userInfo.UserId);
        DataTable dtget_phone = DBHelper.ExecuteDataTable(get_phone);
        if (dtget_phone.Rows.Count > 0)
        {
            string sql = "select loginid,phone from sys_users where phone = '" + dtget_phone.Rows[0]["mobile"].ToString() + "' and ltrim(rtrim(isactive))= 'Y'";
            DataTable dtqx = DBHelper.ExecuteDataTable(sql);
            if (dtqx.Rows.Count > 0)
            {
                //string sqlye = "exec [zdy_查询经销商余额] '{0}'";
                //sqlye = string.Format(sqlye, dtqx.Rows[0]["loginid"].ToString());
                //DataTable dtye = DBHelper.ExecuteDataTable(sqlye);
                //if (dtye.Rows.Count > 0)
                //{
                //    if (Utility.ToDecimal(dtye.Rows[0]["FEECANTAKE"].ToString()) > 0)
                //    {
                        Response.Redirect("views\\Mobile\\main.html?mobile=" + HttpUtility.UrlEncode(dtqx.Rows[0]["phone"].ToString()) + "&customerCode=" + HttpUtility.UrlEncode(dtqx.Rows[0]["loginid"].ToString()) + "");
                //    }
                //    else
                //    {
                //        Response.Write("<script>alert('当前可提货金额不足，无法发布调拨单！')</script>");
                //    }
                //}
                //else
                //{
                //    Response.Write("<script>alert('未查到该经销商余额，请联系管理员！')</script>");
                //}
            }
            else
            {
                Response.Write("<script>alert('不在用户列表中，请联系管理员！')</script>");
            }
        }
        else
        {
            Response.Write("<script>alert('未获取到用户手机号，请联系管理员！')</script>");
        }
    }
    //获取token
    public string GetQiyAccess_token()
    {
        var request = (HttpWebRequest)WebRequest.Create("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + appid + "&corpsecret=" + appsecret + "");
        var response = (HttpWebResponse)request.GetResponse();
        var to = new StreamReader(response.GetResponseStream()).ReadToEnd();
        string access_token = "";
        string strCode = @"\""access_token\"":\s*""(?'access_token'[^""]*)""";
        Regex regex = new Regex(strCode, RegexOptions.IgnoreCase);
        if (regex.IsMatch(to))
        {
            MatchCollection matches = regex.Matches(to);
            StringBuilder stringBuilder = new StringBuilder();
            foreach (Match match in matches)
            {
                access_token = match.Groups["access_token"].Value;
            }
        }
        return access_token;
    }
    //获取用户账号
    public string GetQiyGetUserinfo(string accesstoken, string code)
    {
        var request = (HttpWebRequest)WebRequest.Create("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + accesstoken + "&code=" + code);
        var response = (HttpWebResponse)request.GetResponse();
        var to = new StreamReader(response.GetResponseStream()).ReadToEnd();
        string strUserId = "";
        string strCode = @"\""UserId\"":\s*""(?'UserId'[^""]*)""";
        Regex regex = new Regex(strCode, RegexOptions.IgnoreCase);
        if (regex.IsMatch(to))
        {
            MatchCollection matches = regex.Matches(to);
            StringBuilder stringBuilder = new StringBuilder();
            foreach (Match match in matches)
            {
                strUserId = match.Groups["UserId"].Value;
            }
        }
        return strUserId;
    }
    //获取用户信息，类
    public UserInfo2 GetQiyGetUserinfo2(string accesstoken, string code)
    {
        string userInfoUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + accesstoken + "&code=" + code + "";
        string userInfo = GetJson(userInfoUrl);
        return JsonToEntity<UserInfo2>(userInfo);
    }
    //获取用户详细信息2
    public userdetail getuserdetail2(string accesstoken, string userid)
    {
        string userInfoUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + accesstoken + "&userid=" + userid + "";
        string userInfo = GetJson(userInfoUrl);
        return JsonToEntity<userdetail>(userInfo);
    }
    //获取服务器json数据
    public string GetJson(string url)
    {
        WebClient wc = new WebClient();
        wc.Credentials = CredentialCache.DefaultCredentials;
        wc.Encoding = Encoding.UTF8;
        string returnText = wc.DownloadString(url);
        return returnText;
    }
    /// <summary>  
    /// 获取Json的Model  
    /// </summary>  
    /// <typeparam name="T"></typeparam>  
    /// <param name="szJson"></param>  
    /// <returns></returns>  
    public T JsonToEntity<T>(string szJson)
    {
        T obj = Activator.CreateInstance<T>();
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            return (T)serializer.ReadObject(ms);
        }
    }
}

//用户信息实体类
public class UserInfo2
{

    /// <summary>
    /// errcode 返回码
    /// </summary>		
    private string _errcode;
    public string errcode
    {
        get { return _errcode; }
        set { _errcode = value; }
    }
    /// <summary>
    /// errmsg 对返回码的文本描述内容
    /// </summary>		
    private string _errmsg;
    public string errmsg
    {
        get { return _errmsg; }
        set { _errmsg = value; }
    }
    /// <summary>
    /// UserId 成员UserID
    /// </summary>		
    private string _UserId;
    public string UserId
    {
        get { return _UserId; }
        set { _UserId = value; }
    }
    /// <summary>
    /// DeviceId 手机设备号(由企业微信在安装时随机生成，删除重装会改变，升级不受影响)
    /// </summary>		
    private string _DeviceId;
    public string DeviceId
    {
        get { return _DeviceId; }
        set { _DeviceId = value; }
    }
    /// <summary>
    /// user_ticket 成员票据，最大为512字节。
    /// scope为snsapi_userinfo或snsapi_privateinfo，且用户在应用可见范围之内时返回此参数。
    ///后续利用该参数可以获取用户信息或敏感信息。
    /// </summary>		
    private string _user_ticket;
    public string user_ticket
    {
        get { return _user_ticket; }
        set { _user_ticket = value; }
    }
    /// <summary>
    /// expires_in user_ticket的有效时间（秒），随user_ticket一起返回
    /// </summary>		
    private string _expires_in;
    public string expires_in
    {
        get { return _expires_in; }
        set { _expires_in = value; }
    }
}
public class userdetail
{

    /// <summary>
    /// errcode 返回码
    /// </summary>		
    private string _errcode;
    public string errcode
    {
        get { return _errcode; }
        set { _errcode = value; }
    }
    /// <summary>
    /// errmsg 对返回码的文本描述内容
    /// </summary>		
    private string _errmsg;
    public string errmsg
    {
        get { return _errmsg; }
        set { _errmsg = value; }
    }
    /// <summary>
    /// userid 成员UserID
    /// </summary>		
    private string _userid;
    public string userid
    {
        get { return _userid; }
        set { _userid = value; }
    }
    /// <summary>
    /// name 成员姓名
    /// </summary>		
    private string _name;
    public string name
    {
        get { return _name; }
        set { _name = value; }
    }
    /// <summary>
    /// mobile 成员手机号
    /// </summary>		
    private string _mobile;
    public string mobile
    {
        get { return _mobile; }
        set { _mobile = value; }
    }
    /// <summary>
    /// gender 性别
    /// </summary>		
    private int _gender;
    public int gender
    {
        get { return _gender; }
        set { _gender = value; }
    }
    /// <summary>
    /// email 成员邮箱
    /// </summary>		
    private string _email;
    public string email
    {
        get { return _email; }
        set { _email = value; }
    }
}